package com.badibadi.fragment;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.tsz.afinal.FinalBitmap;

import org.json.JSONException;

import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.ab.bitmap.AbImageDownloader;
import com.badibadi.activity.AfterLandingActivity;
import com.badibadi.activity.MyDataActivity;
import com.badibadi.activity.PicturePreviewActivity;
import com.badibadi.activity.SeeOtherPeopleSpaceActivity;
import com.badibadi.infos.BrowseAllPhoto_Model;
import com.badibadi.infos.PageHomePhotoModel;
import com.badibadi.infos.Results;
import com.badibadi.mytools.BitmapHelp;
import com.badibadi.mytools.Constants;
import com.badibadi.mytools.JSONUtils;
import com.badibadi.mytools.MyThreadTool;
import com.badibadi.mytools.Utils;
import com.badibadi.uniclubber.R;
import com.badibadi.waterfall.LazyScrollView;
import com.badibadi.waterfall.LazyScrollView.OnScrollListener;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer;

//这是登录后的瀑布流
public class WaterFallFragment_1 extends BaseFragment {
	static WaterFallFragment_1 fragment1, fragment2, fragment3;

	private String TAG = "WaterFallFragment";
	private LazyScrollView waterfall_scroll;
	private LinearLayout waterfall_container;
	private ArrayList<LinearLayout> waterfall_items;
	private Display display;
	private DisplayImageOptions options;
	private List<PageHomePhotoModel> list;
	private List<BrowseAllPhoto_Model> AllPhoto_Models;
	private Results results;
	private boolean isScrollview = true;
	// private AssetManager assetManager;
	// private List<String> image_filenames;
	// private final String image_path = "images";

	// private ImageView home, camera, nav_user;

	private int itemWidth;
	private int column_count = 2;// 显示列数
	private int page_count = 12;// 每次加载12张图片
	private int page = 1;// 页码
	private int type = 3;// 1表示默认 2 表示最热 3 表示最新
	private int qidong = 0;

	private int current_page = 0;
	private ViewHolder holder;
	private List<PageHomePhotoModel> homePhotoModels = null;
	// private Button ceshi_xiayiye;
	FinalBitmap finalBitmap;
	private final ColorDrawable TRANSPARENT_DRAWABLE = new ColorDrawable(
			android.R.color.transparent);
	private AbImageDownloader mAbImageDownloader = null;
	private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 1:
				try {
					Utils.ExitPrgress(getActivity());

					// 第一次加载
					homePhotoModels.addAll(list);
//					   
					// waterfall_scroll.scrollTo(1, 1);
					AddItemToContainer(homePhotoModels, current_page,
							page_count * page);
				} catch (Exception e) {
					// TODO: handle exception
				}
				break;
			case 2:
				try {
					Utils.ExitPrgress(getActivity());
					Utils.showMessage(getActivity(),
							getResources().getString(R.string.l_net_error));
					if (page > 1) {
						--page;
					} else {
						page = 1;
					}
				} catch (Exception e) {
					// TODO: handle exception
				}

				break;
			case 3:
				try {
					waterfall_scroll.scrollTo(1, 1);
//					   ("到顶判断");
				} catch (Exception e) {
					// TODO: handle exception
				}

				break;
			case 4:
				try {
					Utils.ExitPrgress(getActivity());
					Utils.showMessage(getActivity(),
							getResources().getString(R.string.wx_txt_72));
				} catch (Exception e) {
					// TODO: handle exception
				}
				if (page > 1) {
					--page;
				} else {
					page = 1;
				}
				break;
			case 5:
				try {
//					   
					((AfterLandingActivity) getActivity()).setAdd_in(1000);
					((AfterLandingActivity) getActivity()).jiazai(10);
					Constants.is_shuaxin = false;
				} catch (Exception e) {
					// TODO: handle exception
					   
				}
				break;
			default:
				break;
			}
		}
	};

	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		display = getActivity().getWindowManager().getDefaultDisplay();
		itemWidth = display.getWidth() / column_count;// 根据屏幕大小计算每列大小
		// assetManager = getActivity().getAssets();
		homePhotoModels = new ArrayList<PageHomePhotoModel>();
		list = new ArrayList<PageHomePhotoModel>();
		finalBitmap = FinalBitmap.create(getActivity());
		finalBitmap.configLoadfailImage(R.drawable.noimage);
		finalBitmap.configLoadingImage(R.drawable.ic_stub);
		

		// Constants.FirstPageData_handler = handler;
		holder = new ViewHolder();
		// mAbImageDownloader = new AbImageDownloader(getActivity());
		// mAbImageDownloader.setErrorImage(R.drawable.noimage);
		// mAbImageDownloader.setLoadingImage(R.drawable.ic_stub);
		// mAbImageDownloader.setType(AbImageUtil.ORIGINALIMG);
		options = new DisplayImageOptions.Builder()
				.showStubImage(R.drawable.ic_stub)
				.showImageForEmptyUri(R.drawable.noimage)
				.showImageOnFail(R.drawable.noimage).cacheInMemory()
				.cacheOnDisc().displayer(new RoundedBitmapDisplayer(0)).build();
		Constants.is_shuaxin = false;
	}

	@Override
	public void onStart() {
		// TODO Auto-generated method stub
		super.onStart();
		if (Constants.is_shuaxin) {
			handler.sendEmptyMessageDelayed(5, 700);
		}
	}

	private void InitLayout(View view) {
		// TODO Auto-generated method stub
		waterfall_scroll = (LazyScrollView) view
				.findViewById(R.id.waterfall_scroll);
		waterfall_scroll.getView();
		waterfall_scroll.setOnScrollListener(new OnScrollListener() {
			@Override
			public void onTop() {
				// 滚动到最顶端
				waterfall_scroll.scrollTo(1, 1);
				// handler.sendEmptyMessage(3);
//				   
//				   
			}

			@Override
			public void onScroll() {
				// 滚动中
//				   
			}

			@Override
			public void onBottom() {
				// 滚动到最低端
				// AddItemToContainer(++current_page, page_count);
				GetPhotoData(++page, type);
			}
		});

		waterfall_container = (LinearLayout) view
				.findViewById(R.id.waterfall_container);
		waterfall_container.setBackgroundColor(0xffeeeeee);
		waterfall_items = new ArrayList<LinearLayout>();
		// 根据column_count列数弄两列linearLayout
		for (int i = 0; i < column_count; i++) {
			LinearLayout itemLayout = new LinearLayout(getActivity());
			LinearLayout.LayoutParams itemParam = new LinearLayout.LayoutParams(
					itemWidth, LayoutParams.WRAP_CONTENT);
			// itemParam.width = itemWidth;
			// itemParam.height = LayoutParams.WRAP_CONTENT;
			itemLayout.setPadding(5, 5, 5, 5);
			itemLayout.setOrientation(LinearLayout.VERTICAL);
			itemLayout.setLayoutParams(itemParam);
			itemLayout.setBackgroundColor(0xffeeeeee);
			waterfall_items.add(itemLayout);
			waterfall_container.addView(itemLayout);
		}
		GetPhotoData(page, type);
		jianting();
		// 加载所有图片路径
		// try {
		// image_filenames = Arrays.asList(assetManager.list(image_path));
		//    
		// } catch (IOException e) {
		//    
		// }
		handler.sendEmptyMessageDelayed(3, 2000);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		type = getArguments().getInt("type");
		//    ("传送过来的类型是:" + type);
		View view = inflater.inflate(R.layout.waterfall_1, null);
		// LoadFragment(qidong);
		InitLayout(view);
		return view;
	}

	private void GetPhotoData(final int page, final int type) {
		Utils.showPrgress(getActivity());
		new Thread(new Runnable() {
			@Override
			public void run() {
				list = new ArrayList<PageHomePhotoModel>();
				Map<String, Object> params = new HashMap<String, Object>();
				params.put("page", page);
				params.put("type", type);
				params.put("pageNum", "12");
				//    ("传过去的参数:" + params.toString());
//				   
				String photocontent = Utils.sendRequest(params,
						Constants.BadiUrl_1 + "Index/home_Page_Info");
				if (photocontent != null) {
					results = Utils
							.checkResult_NNN(getActivity(), photocontent);
					//    ("获取的结果是:" + photocontent);
//					   
					if (results != null && results.getRetmsg() != null) {
						try {
							list = JSONUtils.getListByJsonString(
									results.getRetmsg(),
									PageHomePhotoModel.class);
							handler.sendEmptyMessage(1);
						} catch (JSONException e) {
//							   ("warterfall解析出错");
							   
						}
					} else {
						handler.sendEmptyMessage(4);
					}
				} else {
					handler.sendEmptyMessage(2);
				}
			}
		}).start();
	}

	private void jianting() {
		MyThreadTool.fixedThreadPool.execute(new Runnable() {
			@Override
			public void run() {
				while (isScrollview) {
					try {
						if (waterfall_scroll.getScrollY() < 1) {
							handler.sendEmptyMessage(3);
							//    
							// "+++++++++++++++执行了++++++++++++++++++");
						}
						//    
						// waterfall_scroll.getScrollY());
						Thread.sleep(100);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						   
					}
				}
			}
		});
	}

	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		isScrollview = false;
		//改
		finalBitmap.clearCache();
		finalBitmap.clearDiskCache();
		finalBitmap.clearMemoryCache();
	}

	@Override
	public void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
	}

	private void AddItemToContainer(List<PageHomePhotoModel> homePhotoModels,
			int pageindex, int pagecount) {
		int j = 0;
		int imagecount = homePhotoModels.size();
		//    ("图片有多少个:" + imagecount);
		for (int i = pageindex * pagecount; i < pagecount * (pageindex + 1)
				&& i < imagecount; i++) {
			j = (j >= column_count ? j = 0 : j);
			if (i >= page_count * (page - 1)) {
				AddImage(homePhotoModels, j++, i);
			}
		}
		// handler.sendEmptyMessage(3);
	}

	private void AddImage(final List<PageHomePhotoModel> list,
			final int columnIndex, final int id) {
		// ViewHolder viewHolder = null;
		// if (convertView == null) {
		// convertView = View.inflate(context, R.layout.item_happ_attribute,
		// null);
		// viewHolder = new ViewHolder();
		// viewHolder.itenhapp_title=(TextView)
		// convertView.findViewById(R.id.itenhapp_title);
		// viewHolder.itenhapp_name=(TextView)
		// convertView.findViewById(R.id.itenhapp_name);
		// convertView.setTag(viewHolder);
		// } else {
		// viewHolder = (ViewHolder) convertView.getTag();
		// }
		try {
			holder.layout1 = LayoutInflater.from(getActivity());
			holder.item = holder.layout1.inflate(R.layout.waterfallitem, null)
					.findViewById(R.id.waterfallitemid);
			holder.item.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View arg0) {
					// Toast.makeText(getActivity(),
					// "你点击了id===》" + id + " " + columnIndex, 0).show();
					AllPhoto_Models = new ArrayList<BrowseAllPhoto_Model>();
					BrowseAllPhoto_Model model = new BrowseAllPhoto_Model();
					model.setId(list.get(id).getId());
					model.setPath(list.get(id).getPath());
					AllPhoto_Models.add(model);
					Intent intent = new Intent(getActivity(),
							PicturePreviewActivity.class);
					intent.putExtra("picture_list",
							(Serializable) AllPhoto_Models);
					startActivity(intent);
				}
			});
			holder.zan_num = (TextView) holder.item.findViewById(R.id.zan_num);
			holder.review_num = (TextView) holder.item
					.findViewById(R.id.review_num);
			holder.collection_num = (TextView) holder.item
					.findViewById(R.id.collection_num);
			holder.childern_content = (TextView) holder.item
					.findViewById(R.id.childern_content);
			TextView how_from = (TextView) holder.item
					.findViewById(R.id.how_from);
			final ImageView waterfall_image = (ImageView) holder.item
					.findViewById(R.id.waterfall_image);
			how_from.setText(list.get(id).getNickName());
			holder.zan_num.setText(list.get(id).getView());
			holder.review_num.setText(list.get(id).getDream());
			holder.collection_num.setText(list.get(id).getCollect());
			holder.childern_content.setText(list.get(id).getTitle());
			how_from.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					if (!list.get(id).getUid()
							.equals("" + Utils.getUid(getActivity()))) {
						Intent intent = new Intent(getActivity(),
								SeeOtherPeopleSpaceActivity.class);
						intent.putExtra("friend_id", list.get(id).getUid());
						startActivity(intent);
					} else {
						Intent intent = new Intent(getActivity(),
								MyDataActivity.class);
						// intent.putExtra("friend_id", list.get(id).getUid());
						startActivity(intent);
					}
				}
			});
			try {

				new BitmapHelp().displayImage(getActivity(), waterfall_image,
						Constants.BadiDownImgUrl + list.get(id).getPath()
								+ Constants.appWaterfall);
				// ImageLoader.getInstance().displayImage(
				// Constants.BadiDownImgUrl + list.get(id).getPath()
				// + Constants.appWaterfall, waterfall_image,
				// options);
				// mAbImageDownloader.setType(AbImageUtil.ORIGINALIMG);
				// mAbImageDownloader.display(waterfall_image,
				// Constants.BadiDownImgUrl + list.get(id).getPath()
				// + Constants.appWaterfall);
				//    
				// + list.get(id).getPath() + Constants.appWaterfall);

				// ImageLoader.getInstance().loadImage(uri, targetImageSize,
				// listener);
				// ImageLoader.getInstance().loadImage(
				// Constants.BadiDownImgUrl + list.get(id).getPath()
				// + Constants.appWaterfall, options,
				// new ImageLoadingListener() {
				// // @Override
				// // public void onLoadingComplete(String arg0,
				// // View arg1, Bitmap arg2) {
				// // // TODO Auto-generated method stub
				// // double width = arg2.getWidth();
				// // double height = arg2.getHeight();
				// // double bili = width / height;
				// // double new_h = ((double) itemWidth) / bili;
				// // waterfall_image.setImageBitmap(Utils.scaleImg(
				// // arg2, itemWidth, ((int) new_h)));
				// // }
				//
				// @Override
				// public void onLoadingCancelled(String arg0,
				// View arg1) {
				// // TODO Auto-generated method stub
				//
				// }
				//
				// @Override
				// public void onLoadingFailed(String arg0, View arg1,
				// FailReason arg2) {
				// // TODO Auto-generated method stub
				//
				// }
				//
				// @Override
				// public void onLoadingStarted(String arg0, View arg1) {
				// // TODO Auto-generated method stub
				//
				// }
				//
				// @Override
				// public void onLoadingComplete(String arg0,
				// View arg1, Bitmap arg2) {
				// // TODO Auto-generated method stub
				// // double width = arg2.getWidth();
				// // double height = arg2.getHeight();
				// // double bili = width / height;
				// // double new_h = ((double) itemWidth) / bili;
				// double bmph1=arg2.getHeight();
				// double bmpW1=arg2.getWidth();
				// double bmpW2=itemWidth;
				// double bmmph2=(bmph1*bmpW2)/bmpW1;
				//
				// //原图片的下载
				// // mAbImageDownloader.setWidth(width);
				// // mAbImageDownloader.setHeight(height);
				// //// mAbImageDownloader.display(scaleView,imageUrl);
				// // mAbImageDownloader.display(waterfall_image,
				// Constants.BadiDownImgUrl + list.get(id).getPath()
				// // + Constants.appWaterfall);
				// finalBitmap.display(waterfall_image, Constants.BadiDownImgUrl
				// + list.get(id).getPath()
				// + Constants.appWaterfall, itemWidth, (int)bmmph2);
				// // Bitmap bmp=Utils.scaleImg(arg2, itemWidth, ((int) new_h));
				// //
				// // final TransitionDrawable transitionDrawable = new
				// TransitionDrawable(
				// // new Drawable[] {
				// // TRANSPARENT_DRAWABLE,
				// // new BitmapDrawable(waterfall_image.getResources(),
				// // bmp) });
				// // waterfall_image.setImageDrawable(transitionDrawable);
				// // transitionDrawable.startTransition(300);
				//
				//
				// }
				// });
			} catch (Exception e) {
				   
			}
			waterfall_items.get(columnIndex).addView(holder.item);
		} catch (Exception e) {
			// TODO: handle exception
			   
		}

	}

	private final class ViewHolder {
		public LayoutInflater layout1;
		public TextView zan_num,// 足迹
				review_num,// 梦想
				childern_content,// 图片名字
				how_from,// 来自哪里
				collection_num;// 收藏
		public ImageView like;
		public View item;
		public LinearLayout linearLayout1;
		// private ImageView waterfall_image;
	}

	public static WaterFallFragment_1 getInstance() {
		if (fragment1 == null) {
			return new WaterFallFragment_1();
		}
		return fragment1;
	}

	public static WaterFallFragment_1 getInstance2() {
		if (fragment2 == null) {
			return new WaterFallFragment_1();
		}
		return fragment2;
	}

	public static WaterFallFragment_1 getInstance3() {
		if (fragment3 == null) {
			return new WaterFallFragment_1();
		}
		return fragment3;
	}
}
